<template>
  <div class="editor-form">
    <el-form ref="form" :model="formData" class="editForm">
      <el-collapse v-model="activeNames">
        <h4>活动</h4>
        <el-collapse-item title="满减活动" name="0" class="game-select">
          <div class="selected" v-if="formData.priceReduceId"><span class="value">{{ formData.priceReduceText }}</span>
            <i class="jyfont dj-change el-icon-sort" @click="handleTableList"></i>
            <i class="jyfont dj-not_found icon_custom el-icon-delete" @click="formData.priceReduceId = null"></i>
          </div>
          <el-button v-else type="primary" size="small" @click="productDialogVisible = true"
                     style="width: 90%;margin: auto;display: block">选择满减活动
          </el-button>
        </el-collapse-item>
        <h4>全局设置</h4>
        <el-collapse-item title="展示设置" name="1">
          <el-radio-group v-model="formData.showDevice">
            <el-radio label="all">PC端和手机端</el-radio>
            <el-radio label="desktop">仅PC端</el-radio>
            <el-radio label="mobile">仅手机端</el-radio>
          </el-radio-group>
        </el-collapse-item>
        <el-collapse-item title="遮罩" name="2">
          <el-form-item label="颜色">
            <el-color-picker
                v-model="formData.maskColor"
                show-alpha
                :predefine="predefineColors">
            </el-color-picker>
          </el-form-item>
        </el-collapse-item>
        <h4>内容</h4>
        <el-collapse-item name="3">
          <template slot="title">
            <div class="collapse-item-nowrap">{{ '文本：' + headerText.popupTitle }}</div>
          </template>
          <el-form-item label="" class="editForm-item">
            <quill-editor v-model="formData.popupTitle"
                          ref="myQuillEditor"
                          @ready="onEditorChange($event, 'popupTitle')"
            >
            </quill-editor>
          </el-form-item>
        </el-collapse-item>
        <el-collapse-item name="4">
          <template slot="title">
            <div class="collapse-item-nowrap">{{ '活动方案：' + headerText.programme }}</div>
          </template>
          <el-form-item label="">
            <quill-editor v-model="formData.programme"
                          ref="myQuillEditor"
                          @ready="onEditorChange($event, 'programme')"
            >
            </quill-editor>
            <div style="display: flex;align-items: center">
              <el-link type="primary" :underline="false" @click="handleCopy('{{amount}}')"><span class="variable" v-html="'点击复制变量：{{amount}}'"> </span></el-link>
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content" v-html="'{{amount}}将被系统替换为上方配置的门槛值，{{}}中间的内容请勿修改'"></div>
                <i class="el-icon-question" style="margin-left: 10px"></i>
              </el-tooltip>
            </div>
            <div style="display: flex;align-items: center">
              <el-link type="primary" :underline="false" @click="handleCopy('{{rebate}}')"><span class="variable" v-html="'点击复制变量：{{rebate}}'"> </span></el-link>
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content" v-html="'{{rebate}}将被系统替换为上方配置的门槛值，{{}}中间的内容请勿修改'"></div>
                <i class="el-icon-question" style="margin-left: 10px"></i>
              </el-tooltip>
            </div>
          </el-form-item>
        </el-collapse-item>
        <el-collapse-item name="5">
          <template slot="title">
            <div class="collapse-item-nowrap">{{ '活动说明：' + headerText.description }}</div>
          </template>
          <el-form-item label="">
            <quill-editor v-model="formData.description"
                          ref="myQuillEditor"
                          @ready="onEditorChange($event, 'description')"
            >
            </quill-editor>
          </el-form-item>
        </el-collapse-item>
        <el-collapse-item name="6">
          <template slot="title">
            <div class="collapse-item-nowrap">{{ '按钮：' + headerText.btnText }}</div>
          </template>
          <el-form-item label="">
            <quill-editor v-model="formData.btnText"
                          ref="myQuillEditor"
                          @ready="onEditorChange($event, 'btnText')"
            >
            </quill-editor>
          </el-form-item>
          <el-form-item label="底色">
            <el-color-picker
                v-model="formData.btnBackgroundColor"
                :predefine="predefineColors">
            </el-color-picker>
          </el-form-item>
          <el-form-item label="边框颜色">
            <el-color-picker
                v-model="formData.btnBorderColor"
                :predefine="predefineColors">
            </el-color-picker>
          </el-form-item>
          <el-form-item label="跳转活动页">
            <el-switch
                v-model="formData.showBtn"
                active-color="#1e90ff">
            </el-switch>
          </el-form-item>
        </el-collapse-item>
        <el-collapse-item title="关闭按钮" name="7">
          <el-form-item label="颜色">
            <el-color-picker
                v-model="formData.btnColor"
                :predefine="predefineColors">
            </el-color-picker>
          </el-form-item>
        </el-collapse-item>
        <el-collapse-item title="优惠券" name="8">
          <el-form-item label="颜色">
            <el-color-picker
                v-model="formData.popupColor"
                :predefine="predefineColors">
            </el-color-picker>
          </el-form-item>
        </el-collapse-item>
        <h4>背景</h4>
        <el-collapse-item title="底图" name="9">
          <el-form-item label="底色1">
            <el-color-picker
                v-model="formData.baseMap1"
                :predefine="predefineColors">
            </el-color-picker>
          </el-form-item>
          <el-form-item label="底色2">
            <el-color-picker
                v-model="formData.baseMap2"
                :predefine="predefineColors">
            </el-color-picker>
          </el-form-item>
          <el-form-item label="图片" prop="imageUrl" class="no-border pic">
            <ele-form-upload-plus-file v-model="formData.imageUrl" title="图片" ref="imageSelect"   />
          </el-form-item>
          <el-form-item label="样式" class="editForm-item" style="margin: 20px" v-if="formData.imageUrl">
            <el-select v-model="formData.bgStyle" placeholder="样式">
              <el-option label="自适应" value="bg-selfAdaption"></el-option>
              <el-option label="填充" value="bg-fill"></el-option>
              <el-option label="拉伸" value="bg-stretching"></el-option>
              <el-option label="平铺" value="bg-tile"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="对齐" class="editForm-item" style="margin: 20px" v-if="formData.imageUrl">
            <el-select v-model="formData.bgAlignment" placeholder="对齐">
              <el-option label="居中" value="bg-center"></el-option>
              <el-option label="左上" value="bg-left-top"></el-option>
              <el-option label="右上" value="bg-right-top"></el-option>
              <el-option label="左下" value="bg-left-bottom"></el-option>
              <el-option label="右下" value="bg-right-bottom"></el-option>
            </el-select>
          </el-form-item>
        </el-collapse-item>
      </el-collapse>
      <el-form-item style="text-align: right;margin-top: 20px">
        <el-button @click="handleResetStyle()">重置样式</el-button>
        <el-button @click="$emit('on-cancel')">取消</el-button>
        <el-button type="primary" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
    <el-dialog title="选择满减活动" :visible.sync="productDialogVisible">
      <div class="search-list">
        <el-form ref="form" class="search-table-form" :model="formParams" label-width="90px" size="small"
                 style="background: #fff;padding: 10px">
          <div style="display: flex;align-items: center">
            <el-form-item label="活动名称：" style="margin-bottom: 0;margin-right: 20px">
              <el-input v-model="formParams.name" placeholder="请输入"  @keyup.enter.native="handleSearch"  style="width: 100%"></el-input>
            </el-form-item>
            <div style="display: flex;align-items: center">
              <el-button size="small" type="primary" @click="handleSearch">搜索查询</el-button>
              <el-button size="small" type="default" @click="handleRest">重置</el-button>
            </div>
          </div>
        </el-form>
      </div>
      <el-table :data="tableData" ref="listTable" style="width: 100%" stripe v-loading="loadingTable" element-loading-text="加载中"
                highlight-current-row @row-click="handleCurrentRow">
        <el-table-column label="选择" width="50px">
          <template slot-scope="scope">
            <el-radio class="no-label" v-model="indexRow" :label="scope.row.id" :key="'radio' + scope.$index"
                      @change="currentRow(scope.$index, scope.row)"></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称"/>
        <el-table-column label="活动时间">
          <template slot-scope="scope">
            {{
              scope.row.startTime|utcFormat('YYYY-MM-DD HH:mm:ss', timeZone)
            }} ~ <span v-if="scope.row.endTime==undefined">永不过期</span>
            <span v-if="scope.row.endTime!=undefined">
          {{ scope.row.endTime|utcFormat('YYYY-MM-DD HH:mm:ss', timeZone) }}
        </span>
          </template>
        </el-table-column>
        <el-table-column prop="reduceRule" label="优惠项">
          <template slot-scope="{row}">
            <span v-html="row.reduceRule"></span>
          </template>
        </el-table-column>
        <el-table-column prop="reduceGoods" label="适用商品"/>
        <el-table-column prop="statusText" label="活动状态"/>
      </el-table>
      <el-pagination
          class="pagination"
          background
          @current-change="handleCurrentChange"
          :current-page="formParams.page"
          layout="total, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
    <el-button @click="productDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveProductList">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import {getPriceReducePage} from '@/api/priceReduce';
import {mapGetters} from 'vuex';

import configDefaultItems from '../../../config/subscriptionPopus';

export default {
    name: 'Form',
    components: {},
    props: {
        value: {
            type: Object,
            default: () => ({})
        },
        resetStyle: {
            type: Boolean,
            default: false
        }
    },
    data () {
        return {
            indexRow: null,
            productDialogVisible: false,
            total: 0,
            formParams: {
                name: '',
                page: 1,
                pageSize: 20,
                status: 'unfinished'
            },
            tableData: [],
            activeNames: [],
            loadingTable: false,
            formData: this.$props.value ? JSON.parse(JSON.stringify(this.$props.value)) : {},
            formDataBase: this.$props.value ? JSON.parse(JSON.stringify(this.$props.value)) : {},
            uploadPath: process.env.VUE_APP_BASE_API + '/upload-file',
            predefineColors: [
                '#ff4500',
                '#ff8c00',
                '#ffd700',
                '#90ee90',
                '#00ced1',
                '#1e90ff',
                '#c71585',
                'rgba(255, 69, 0, 0.68)',
                'rgb(255, 120, 0)',
                'hsv(51, 100, 98)',
                'hsva(120, 40, 94, 0.5)',
                'hsl(181, 100%, 37%)',
                'hsla(209, 100%, 56%, 0.73)'
            ],
            headerText: {
                popupTitle: '',
                programme: '',
                description: '',
                btnText: ''
            },
            rules: {
                link: [
                    {required: true, message: '请输入活动链接', trigger: 'blur'}
                ]
            }
        };
    },
    computed: {
        siteId () {
            return this.$store.state.user.siteId;
        },
        ...mapGetters(['timeZone'])
    },
    watch: {
        formData: {
            deep: true,
            handler (value) {
                console.log(value);
                if (value.showBtn === undefined) {
                    value.showBtn = true;
                }
                this.$emit('input', value);
                this.$emit('on-change', value);
            }
        }
    },
    mounted () {
        this.initData();
    },
    methods: {
        handleResponse (response, file, fileList) {
            return response;
        },
        initData () {
            getPriceReducePage({...this.formParams, siteId: this.siteId}).then(res => {
                this.tableData = res.records;
                if (this.formData.link === '') {
                    this.formData.link = '/rebate/' + this.tableData[0].id + '?type=PRICE_REDUCE';
                }
                this.total = res.totalElements;
                this.getParams();
            });
        },
        currentRow (index, row) {
            this.indexRow = row.id;
            this.formData.link = '/rebate/' + row.id + '?type=PRICE_REDUCE ';
        },
        handleCurrentRow (row, column, event) {
            this.indexRow = row.id;
            this.formData.link = '/rebate/' + row.id + '?type=PRICE_REDUCE';
        },
        handleCurrentChange (val) {
            this.formParams.page = val;
            this.initData();
        },
        handleSearch () {
            this.initData();
        },
        handleRest () {
            this.formParams = {
                name: '',
                page: 1,
                pageSize: 20,
                status: 'unfinished'
            };
            this.initData();
        },
        getParams () {
            if (this.formData.priceReduceId) {
                let row = this.tableData.find(res => res.id === this.formData.priceReduceId);
                if (!row) {
                    this.formData.priceReduceId = null;
                    return;
                }
                this.formData.startTime = row.startTime;
                this.formData.endTime = row.endTime;
                this.formData.priceReduceType = row.type;
                this.formData.priceReduceText = row.name;
                this.formData.levelJson = JSON.parse(row.levelJson);
            }
        },
        handleTableList () {
            this.productDialogVisible = true;
            let row = this.tableData.find(res => res.id === this.formData.priceReduceId);
            this.$nextTick(() => {
                this.$refs.listTable.setCurrentRow(row);
                this.indexRow = row.id;
            });
        },
        saveProductList () {
            this.formData.priceReduceId = this.indexRow;
            this.getParams();
            this.productDialogVisible = false;
        },
        onEditorChange (quill, name) {
            this.headerText[name] = quill.container.innerText;
        },
        async onSubmit () {
            if (this.formData.priceReduceId === null) {
                window.alert('请选择满减活动');
                return false;
            }
            await this.$refs.form.validate();
            this.$emit('on-submit', this.formData);
        },
        handleCopy (recordValue) {
            this.$copyText(recordValue).then((e) => {
                this.$message({
                    message: '复制成功',
                    type: 'success'
                });
            });
        },
        handleResetStyle () {
            if (this.$props.resetStyle) {
                let datalist = configDefaultItems.filter(v => v.name === 'ReductionActivity');
                Object.assign(this.formData, datalist[0].value);
            } else {
                Object.assign(this.formData, this.formDataBase);
            }
        }
    }
};
</script>

<style scoped lang="scss">
.game-select {
  .selected {
    height: 32px;
    border-radius: 2px;
    background-color: #eef0f2;
    line-height: 32px;
    display: flex;
    padding-left: 10px;
    align-items: center;

    .value {
      flex: 1;
      height: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
      white-space: nowrap;
    }

    i {
      width: 32px;
    }
  }
}

.pagination {
  margin-top: 12px;
  text-align: right;
}

.editForm-item-area {
  min-width: 300px!important;
}
</style>
